package com.ruoyi.common.utils.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;

public class ExcelProcess {
    public static Workbook checkExcel(InputStream inputStream) {
        Workbook workbook = null;
        // 自动检测文件格式
        if (inputStream.markSupported()) {
            inputStream.mark(8); // 标记以便重置
            byte[] header = new byte[8];
            try {
                if (inputStream.read(header) != -1) {
                    inputStream.reset(); // 重置流
                    // 检查文件签名
                    if (isXLSFormat(header)) {
                        workbook = new HSSFWorkbook(inputStream); // .xls格式
                    } else {
                        workbook = new XSSFWorkbook(inputStream); // .xlsx格式
                    }
                } else {
                    workbook = new XSSFWorkbook(inputStream); // 默认使用XSSF
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                // 如果不支持mark，尝试使用WorkbookFactory自动检测
                workbook = WorkbookFactory.create(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return workbook;
    }

    // 检查是否为.xls格式（OLE2格式）
    private static boolean isXLSFormat(byte[] header) {
        // .xls文件的签名：D0 CF 11 E0 A1 B1 1A E1
        return header[0] == (byte) 0xD0 && header[1] == (byte) 0xCF && header[2] == (byte) 0x11 && header[3] == (byte) 0xE0 && header[4] == (byte) 0xA1 && header[5] == (byte) 0xB1 && header[6] == (byte) 0x1A && header[7] == (byte) 0xE1;
    }
}
